<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class permission_model extends MY_Model {
	
	protected $table 		= "permissions";
	protected $table2 		= "role_permission";
	protected $key			= "id";
	protected $soft_deletes	= false;
	protected $date_format	= "datetime";
	protected $set_created	= false;
	protected $set_modified = false;
	protected $orderby 		= "controller";

	//---------------------------------------------------------------
	
	// Get list of all allowed permissions id's
	function get_role_permission($role_id=NULL)
	{
	 $this->db->select('*');
	 $this->db->from($this->table2);
	 if($role_id)
		$this->db->where('role_id', $role_id);
	 $list = $this->db->get();
	 return $list;
	}
	
	function get_permission($permission_id)
	{
		$this->db->select('*');
		$this->db->from($this->table);
		$this->db->where('id', $permission_id);
		
		return $this->db->get()->result();	
	}

	function add_role_permission($role_id, $permission_id)
	{
		// Delete all records regarding to role id
		$result = $this->db->delete($this->table2, array('role_id' => $role_id));
		if ($result)
		{
			$del = true;
		} 
		
		
		//Add New rows
		$result = true;
		if(is_array($permission_id)){
		foreach($permission_id as $row){
			$result = $this->db->insert($this->table2, array('role_id'=>$role_id, 'permission_id'=>$row));
			if(!$result)
				return false;
		}}
		return True;
	} 

	function delete($id)
	{
		// 1st check if this permission connected to one or more role
		// if it is connected return false
		// if it is free return true
		$this->db->select('*');
		$this->db->from($this->table2);
		$this->db->where('permission_id',$id);
		$del = $this->db->count_all_results();
		//echo $del;
		//die;
		if(!is_int($del) || $del >= 1)
			return false;
		
		$this->db->where('id', $id);
		return $this->db->delete($this->table); 
		
		
	}
}
